<?php
/* This notice must be untouched at all times.

export.php    v. 2.2
This file is part of PhyloGeoViz
The latest version is available at
http://www.phylogeoviz.com

Copyright (c) 2007 Yi-Hsin Erica Tsai. All rights reserved.
Created 15.7.2007 by Yi-Hsin Erica Tsai (Web: http://www.duke.edu/~yet2)
Last modified: 20.8.2007

PhyloGeoViz is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

PhyloGeoViz is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
	header('Content-type: application/vnd.google-earth.kml+xml'); //identifies the file type as a kml file
	header("Content-Disposition: attachment; filename=\"pies_".date('m-d-y_H-i-s').".kml\"");  //default name of file
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
?>
<kml xmlns="http://earth.google.com/kml/2.1">
<!-- Comments here! -->
<?php
// $_REQUEST is the global array that contains the submitted data.
// The array has an element for each form variable that was submitted.
// In our case we just have the text area, so count($_REQUEST) = 1.
// You can reference elements in the arrays by more than their numerical
// location.  You can call them by their "name". Ex: $_REQUEST["phylodata"]

$res = 5; //resolution of the circles.  Value is number of degrees between pie vertices

function pv ($var)
{
	echo "<pre>";
	var_dump($var);
	echo "</pre>";
}

// hap_vertices -- a function that returns a 2D array of all the vertices for each haplotype for a single pie.  1st D = haplotype, 2nd D = vertices set. 3rd D is x,y coordinates (in degrees)
// This function is based on ink_polaroid's algorithm at http://bbs.keyhole.com/ubb/showflat.php/Cat/0/Number/23634/page/vc/fpart/all/vc/1
function hap_vertices($numhaps, $center, $r, $thetacutoffs)
{
	global $res;  //brings $res into scope (php has silly global variable syntax)
	// convert coordinates to radians
	$lat1 = deg2rad($center->y);
	$long1 = deg2rad($center->x);
	$d_rad = $r*1000/6378137;  //converts to radians? or at least the right coordinates, 6378137 is the Earth's circumference.

	$vertices = array(); 
	
	for ($j = 0; $j < $numhaps; $j++)  //loop over all haplotypes/slices
	{
		$vertices[$j] = array();
		
		//define the start and end of each slice
		$starttheta = round($thetacutoffs[$j]/$res) * $res + 90; //have to add 90 deg because google earth starts 0 theta from vertical instead of horizontal like google maps
		$endtheta = round($thetacutoffs[$j+1]/$res) * $res + 90;
		$natcounter = 0; //2nd counter so array indices are sequential integers
		
		$vertices[$j][$natcounter] = array();
		//add the central point
		$vertices[$j][$natcounter]["x"] = $center->x;
		$vertices[$j][$natcounter]["y"] = $center->y;
		$natcounter++;
		
		for ($i = $starttheta; $i <= $endtheta; $i = $i + $res)  //vertices every 5 degrees
		{
			$theta = deg2rad($i);
			$lat_rad = asin(sin($lat1)*cos($d_rad) + cos($lat1)*sin($d_rad)*cos($theta));
			$dlon_rad = atan2(sin($theta)*sin($d_rad)*cos($lat1), cos($d_rad)-sin($lat1)*sin($lat_rad));
			$lon_rad = fmod(($long1+$dlon_rad + M_PI), 2*M_PI) - M_PI;
			$vertices[$j][$natcounter]["x"] = rad2deg($lon_rad);
			$vertices[$j][$natcounter]["y"] = rad2deg($lat_rad);
			$natcounter++;
		}
		$vertices[$j][$natcounter]["x"] = $center->x;
		$vertices[$j][$natcounter]["y"] = $center->y;
	}

	return $vertices;
}
$numpops = $_REQUEST["expnumpops"];
$numhaps = $_REQUEST["expnumhaps"];
$pop_names = json_decode(stripslashes($_REQUEST["exppop_names"]));
//had to add stripslashes() because the server php json was escaping quotes, then messing up decode.
$hap_names = json_decode(stripslashes($_REQUEST["exphap_names"]));
$pop_centers = json_decode(stripslashes($_REQUEST["exppop_centers"])); //json_decode is the php function that parses encoded JSON objects (evalJSON() was the javascript function)
$pop_haps = json_decode($_REQUEST["exppop_haps"]);
$hapgroups = json_decode(stripslashes($_REQUEST["exphapgroups"]));
$pop_include = json_decode($_REQUEST["exppop_include"]);
$pop_radii = json_decode(stripslashes($_REQUEST["exppop_radii"]));
$hap_colors = json_decode(stripslashes($_REQUEST["exphap_colors"]));
$pop_hapthetas = json_decode($_REQUEST["exppop_hapthetas"]);
$pop_hap_vertices = array();
$outlines = $_REQUEST["outline_checked"];
//fill out vertices data structure
for ($p = 0; $p < $numpops; $p++)
{
	$pop_hap_vertices[$p] = hap_vertices($numhaps, $pop_centers[$p], $pop_radii[$p], $pop_hapthetas[$p]);
}
?>

<Document>
	<name>pies_<?php echo date('m-d-y_H:i:s'); ?>.kml</name>  <!-- generates a random name for the file based on the timestamp -->
	<description>
	<![CDATA[ Pie charts of haplotype distributions.  Generated through <a href="https://www.nescent.org/wg_phyloinformatics/PhyloSoC:phylogeoviz">Phylogeoviz</a>.  Document created <?php echo date('m-d-y') ?> at <?php echo date('H:i:s T') ?>.]]>
	</description>
	<Style id="sn_ylw-circle">  <!-- style for just the placemarks -->
		<IconStyle>
			<Icon>
				<href>http://maps.google.com/mapfiles/kml/paddle/ylw-circle.png</href>
			</Icon>
		</IconStyle>
		<LineStyle>
			<color>ffff0000</color>
		</LineStyle>
		<PolyStyle>
			<color>d9003dff</color>
		</PolyStyle>
	</Style>
	
	<!-- styles for pie slices, i.e. hap colors -->
<?php

	for ($i = 0; $i < $numhaps; $i++)
	{
		echo "\t<Style id=\"stylehap".($i+1)."\">\n";  // use \" as escape character for "
		//hapcolors are their number, not their array indice
?>
		<IconStyle>
			<Icon>
				<href>http://maps.google.com/mapfiles/kml/pal2/icon7.png</href>
			</Icon>
		</IconStyle>
		<LineStyle>
			<color>ff000000</color>
			<width>1.0</width>
		</LineStyle>
		<PolyStyle>
<?php 
		echo "\t\t\t<color>ff".substr($hap_colors[$i], -2, 2).substr($hap_colors[$i], 3, 2).substr($hap_colors[$i], 1, 2)."</color>\n";  
		if($outlines == "true")  //if want outlines, draw outlines
			echo "\t\t\t<outline>1</outline>\n";
		else
			echo "\t\t\t<outline>0</outline>\n";
?>
		</PolyStyle>
	</Style>
<?php
	}

?>	
	<!-- Generate placemarks at all the pop centers -->
	<Folder>
		<name>population labels</name>
<?php
	for ($i = 0; $i < $numpops; $i++)
	{
		if($pop_include[$i] != 0)  //only print if is included
		{

			echo "\t\t<Placemark>\n";
			echo "\t\t\t<name>".$pop_names[$i]."</name>\n"; //pop names are as given by the user
?>
				<description>Further info on the population would go here</description>
				<styleUrl>#msn_ylw-circle</styleUrl>
				<Point>
<?php

			echo "\t\t\t\t<coordinates>".$pop_centers[$i]->x.",".$pop_centers[$i]->y.",0</coordinates>\n";
?>
				</Point>
			</Placemark>
<?php
		}
	}
?>
	</Folder>

	<Folder>
		<name>population pies</name>
		<description>Each locality has a pie where each slice represents the proportion of a haplotype in the population.  Pie slices are organized by haplotype (instead of grouped together by population) to facilitate changing colors and turning on and off pie pieces.</description>
<?php
	for ($h = 0; $h < $numhaps; $h++)
	{
		//group haplotypes by their haplotype group.  Each group in a different folder.
		if ($h == 0)  //is the first hap group
			echo "\t\t<Folder>\n\t\t\t<name>".$hapgroups[$h]."</name>\n";  
		else if ($hapgroups[$h] != $hapgroups[$h - 1])  //belongs in new hapgroup folder
		{
			echo "\t\t</Folder>\n";
			echo "\t\t<Folder>\n\t\t\t<name>".$hapgroups[$h]."</name>\n";  
		}
		//else, do nothing
		
		//put all haplotypes in different sub folders
		echo "\t\t\t<Folder>\n\t\t\t\t<name>".$hap_names[$h]."</name>\n";  //hap name != hap index, hap name == hap index + 1
		
		//create polygons for each haplotype wedge within each pop
		//only create polygons for populations that have that haplotype
		for ($p = 0; $p < $numpops; $p++)
		{
			if($pop_include[$p] != 0 && $pop_haps[$p][$h] > 0)
			{
				echo "\t\t\t\t<Placemark>\n\t\t\t\t\t<name>".$pop_names[$p]."</name>\n";
				echo "\t\t\t\t\t<styleUrl>#stylehap".($h+1)."</styleUrl>\n";
				echo "\t\t\t\t\t<Polygon>\n\t\t\t\t\t\t<outerBoundaryIs>\n\t\t\t\t\t\t\t<LinearRing>\n\t\t\t\t\t\t\t\t<coordinates>\n";

				//write out each vertice
				for ($v = 0; $v < count($pop_hap_vertices[$p][$h]); $v++)
				{
					echo "\t\t\t\t\t\t\t\t\t".$pop_hap_vertices[$p][$h][$v]["x"].", ".$pop_hap_vertices[$p][$h][$v]["y"].", 0\n";
				}
			
				echo "\t\t\t\t\t\t\t\t</coordinates>\n\t\t\t\t\t\t\t</LinearRing>\n\t\t\t\t\t\t</outerBoundaryIs>\n\t\t\t\t\t</Polygon>\n\t\t\t\t</Placemark>\n";
			}
		}
		echo "\t\t\t</Folder>\n";
	}
	echo "\t\t</Folder>\n";

?>
	</Folder>
</Document>
</kml>